/**
 * 
 */
package vn.smartware.co.framework.action;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import vn.smartware.co.framework.bean.LoginDTO;
import vn.smartware.co.framework.connection.ConnectAction;
import vn.smartware.co.framework.connection.HTTPConnectAction;
import vn.smartware.co.framework.exception.ClientException;
import vn.smartware.co.framework.exception.FatalException;
import vn.smartware.co.framework.exception.ServerException;
import vn.smartware.co.framework.exception.SessionTimeOutException;
import vn.smartware.co.framework.form.ActionForm;


/**
 * RequestProcesser Class
 * @author thuctt
 * created 2009/09/01
 */
public class RequestProcesser extends ClientAction {

	private static Log log = LogFactory.getLog(RequestProcesser.class);
	
	/**
	 * Send Repuest. Recevie Responce.
	 * @param form 
	 * @return ActionForm
	 * @throws FatalException 
	 * @throws ServerException 
	 * @throws SessionTimeOutException 
	 */
	public ActionForm processActionPerform(ActionForm form)
			throws FatalException, ServerException, SessionTimeOutException {
		
		try{
			form = createClientUserVO(form);
			
		}catch (ClientException e) {
			throw new FatalException("RequestProcesser processActionPerform ClientException. " + e);
		}
		
		ConnectAction action = new HTTPConnectAction(fileResource);
		form = action.executeRequest(form);
		
		return form;
	}

	/**
	 * Validate Receive Bean.
	 * @param form 
	 * @throws ClientException 
	 */
//	public void processValidator(ActionForm form) throws ClientException {
//	
//		ValidatorForm validator = new ValidatorForm();
//		validator.validate(form, fileResource.getValidator());
//	}
	
	/**
	 * 
	 * createClientUserVO: 
	 * @param form
	 * @return ActionForm
	 * @throws ClientException
	 */
	private ActionForm createClientUserVO(ActionForm form) throws ClientException {
		
		InetAddress host = null;
		String hostName = null;
		String ipAddress = null;
		
		try {
			
			host = InetAddress.getLocalHost();
			
			hostName = host.getHostName();
			ipAddress = host.getHostAddress();
			
			LoginDTO user = (LoginDTO)form.getUserDTO();
			
			if (user == null) {
				user = LoginDTO.getInstance();
			}
			
			user.setMachineName(hostName);
			user.setIpAddress(ipAddress);
			String OS = System.getProperty("os.name");
			String OSversion = System.getProperty("os.version");
			String OSarch = System.getProperty("os.arch");
			user.setOSDescription(OS + ", " + OSversion + ", " + OSarch);
			user.setLoginNo(LoginDTO.getInstance().getLoginNo());
			
			form.setUserDTO(user);
			
		} catch (UnknownHostException e) {
			log.error("LocalHost info get Error.", e);
			throw new ClientException("LocalHost info get Error.", e);
		}
		
		return form;
	}

}
